package com.genersoft.iot.vmp.gb28181.utils;

import org.springframework.util.DigestUtils;
import org.springframework.util.StringUtils;

import java.util.HashMap;
import java.util.Map;
import java.util.TreeMap;

public class SignUtil {
    public static String createSign(Map<String, String> params, String privateKey) {
        if (StringUtils.isEmpty(privateKey))
            return null;
        StringBuilder sb = new StringBuilder();
        Map<String, String> sortParams = new TreeMap<>(params);
        for (Map.Entry<String, String> entry : sortParams.entrySet()) {
            String key = entry.getKey();
            String value = entry.getValue();
            if (!StringUtils.isEmpty(value) && !StringUtils.isEmpty(value.trim()))
                sb.append("&").append(key).append("=").append(value.trim());
        }
        String stringA = sb.toString().replaceFirst("&", "");
        String stringSignTemp = stringA + "&" + "key=" + privateKey;
        System.out.println("sign      " + stringSignTemp);
        String signValue = DigestUtils.md5DigestAsHex(stringSignTemp.getBytes()).toUpperCase();
        return signValue;
    }

    public static boolean signCheck(Map<String, String> params, String privateKey, String sign) {
        String signNew = createSign(params, privateKey);
        if (!StringUtils.isEmpty(signNew) && signNew.equals(sign))
            return true;
        return false;
    }

    public static void main(String[] args) {
        Map<String, String> params = new HashMap<>();
        params.put("deviceId", "34020000001320000005");
        Long curTime = Long.valueOf(System.currentTimeMillis() / 1000L);
        params.put("guardCmdStr", "SetGuard");
//        params.put("timerFlag", "1");
//        params.put("startTime", "20:00");
//        params.put("type", "day");
//        params.put("endTime", "7:00");
        params.put("time", "1637568877");
        System.out.println(createSign(params, "9af0a2dba1a34fc291d6cf9dfcb33c54"));
        System.out.println(signCheck(params, "998877", "FC0979465C1D29D536E6A30B886AFF6D"));
        System.out.println(curTime);
    }
}